package cn.kooki.app.duobao.ui.Fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseFragment;
import cn.kooki.app.duobao.base.BaseRecyclerAdapter;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.Index.GoodsItem;
import cn.kooki.app.duobao.data.Bean.Index.IndexGoodResponse;
import cn.kooki.app.duobao.data.Bean.cart.CartInfo;
import cn.kooki.app.duobao.data.bus.ChangePageEvent;
import cn.kooki.app.duobao.ui.Activity.Goods.GoodsDetailAcitvity;
import cn.kooki.app.duobao.ui.Activity.User.BindActivity;
import cn.kooki.app.duobao.ui.Activity.User.LoginActivity;
import cn.kooki.app.duobao.ui.Activity.Pay.OrderAcitvity;
import cn.kooki.app.duobao.ui.Adapter.ListRecommAdapter;
import cn.kooki.app.duobao.ui.widget.CustomRelativeLayout;
import cn.kooki.app.duobao.ui.widget.NumberPicker;

import cn.kooki.app.duobao.util.PhoneCheckUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.StringUtils;
import cn.kooki.app.duobao.util.manager.CartObserver;
import cn.kooki.app.duobao.util.manager.ShopCartManager;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;


/**
 * Created by xiong on 2015/11/25.
 */
public class CartFragment extends BaseFragment implements CartObserver, View.OnClickListener {
    @Bind(R.id.top_back)
    ImageButton topBack;
    @Bind(R.id.top_text_center)
    TextView topTextCenter;
    @Bind(R.id.top_refresh)
    ImageButton topRefresh;
    @Bind(R.id.top_cart)
    ImageButton topCart;
    @Bind(R.id.action_edit)
    TextView actionEdit;
    @Bind(R.id.toolbar)
    RelativeLayout toolbar;
    @Bind(R.id.notice_icon)
    ImageView noticeIcon;
    @Bind(R.id.notice_more)
    ImageView noticeMore;
    @Bind(R.id.notice_text)
    TextView noticeText;
    @Bind(R.id.notice_wrapper)
    RelativeLayout noticeWrapper;
    @Bind(R.id.cart)
    ListView cart;
    @Bind(R.id.swipe_refresh_layout)
    FrameLayout swipeRefreshLayout;
    @Bind(R.id.submit)
    Button submit;
    @Bind(R.id.amount)
    TextView amount;
    @Bind(R.id.money)
    TextView money;
    @Bind(R.id.amount_wrapper)
    LinearLayout amountWrapper;
    @Bind(R.id.prmote_amount)
    TextView prmoteAmount;
    @Bind(R.id.footer)
    RelativeLayout footer;
    @Bind(R.id.list_recommend)
    RecyclerView listRecommend;
    @Bind(R.id.rcmd)
    LinearLayout rcmd;
    @Bind(R.id.go)
    Button go;
    @Bind(R.id.empty)
    LinearLayout empty;
    @Bind(R.id.layout)
    CustomRelativeLayout layout;
    @Bind(R.id.cart_multi_view_stub)
    ViewStub cartMultiViewStub;

    ImageButton cartMultiCheckbox;

    TextView cartMultiSummary;

    Button cartMultiDelBtn;
    private CartAdapter adapter;

    private boolean isEditing = false;
    private boolean isAllSelected = false;
    private View view;
    private View checkedFooter;
    private String cart_number_desc;
    private String cart_money_desc;

    private ArrayList<GoodsItem> tuijianlist = new ArrayList<>();
    private ListRecommAdapter listRecommAdapter;

    @Override
    public View setView(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.fragment_cart, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void afterView() {
        topTextCenter.setText(R.string.cart);
        topTextCenter.setVisibility(View.VISIBLE);
        adapter = new CartAdapter();
        ShopCartManager.getInstance().changeObservable.registerObserver(this);
        cart.setAdapter(adapter);
        actionEdit.setOnClickListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        listRecommend.setLayoutManager(layoutManager);
        listRecommAdapter = new ListRecommAdapter(context);
        listRecommend.setAdapter(listRecommAdapter);
        listRecommAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                GoodsItem item = (GoodsItem) data;
                Intent intent = new Intent(context, GoodsDetailAcitvity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("qishu", item.getQishu());
                context.startActivity(intent);
            }
        });
        cart_number_desc = getString(R.string.cart_number_desc);
        cart_money_desc = getString(R.string.cart_money_desc);
        gettuijian();
        submit.setOnClickListener(this);


    }

    /**
     * 获取推荐商品
     */
    private void gettuijian() {
        MainFactory.getApiInstance().tuijianlist(new Callback<IndexGoodResponse>() {
            @Override
            public void success(IndexGoodResponse indexGoodResponse, Response response) {
                if (indexGoodResponse.getData() != null) {
                    listRecommAdapter.mDatas.clear();
                    listRecommAdapter.addDatas(indexGoodResponse.getData());
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            checkShowing();
            adapter.notifyDataSetChanged();
        }
    }


    private void checkShowing() {
        int size = ShopCartManager.getInstance().getCartsSize();
        if (size > 0) {
            empty.setVisibility(View.GONE);
            rcmd.setVisibility(View.GONE);
            actionEdit.setText(!isEditing ? R.string.action_edit : R.string.action_done);
            actionEdit.setVisibility(View.VISIBLE);
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            footer.setVisibility(View.VISIBLE);
            amount.setText(String.format(cart_number_desc, size));
            money.setText(String.format(cart_money_desc, ShopCartManager.getInstance().getToalCount()));
        } else {
            swipeRefreshLayout.setVisibility(View.GONE);
            empty.setVisibility(View.VISIBLE);
            rcmd.setVisibility(View.VISIBLE);
            actionEdit.setText(R.string.action_edit);
            actionEdit.setVisibility(View.GONE);
            go.setOnClickListener(this);
            isEditing = false;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        ShopCartManager.getInstance().changeObservable.unregisterObserver(this);
    }


    public void switchshowing(int size) {
        if (size > 0) {
            empty.setVisibility(View.GONE);
            rcmd.setVisibility(View.GONE);
            actionEdit.setText(!isEditing ? R.string.action_edit : R.string.action_done);
            actionEdit.setVisibility(View.VISIBLE);
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            footer.setVisibility(View.VISIBLE);
            amount.setText(String.format(cart_number_desc, size));
            money.setText(String.format(cart_money_desc, ShopCartManager.getInstance().getToalCount()));
        } else {
            swipeRefreshLayout.setVisibility(View.GONE);
            empty.setVisibility(View.VISIBLE);
            rcmd.setVisibility(View.VISIBLE);
            actionEdit.setText(R.string.action_edit);
            actionEdit.setVisibility(View.GONE);
            isEditing = false;
        }

    }

    @Override
    public void onChanged(int count) {
        money.setText(String.format(cart_money_desc, count));

    }

    @Override
    public void onCheckedChange(int count, boolean isCancelEditing) {

        if (count == 0 && isCancelEditing) {
            isEditing = false;
            changeEditing();
        }
        String selectedstring = getString(R.string.cart_multi_summary);
        selectedstring = String.format(selectedstring, count);
        if (cartMultiSummary != null) {
            cartMultiSummary.setText(selectedstring);
        }
        int cartsSize = ShopCartManager.getInstance().getCartsSize();
        if (count == cartsSize) {
            isAllSelected = true;
        } else {
            isAllSelected = false;
        }
        if (cartsSize == 0) isAllSelected = false;
        if (cartMultiCheckbox != null) {
            cartMultiCheckbox.setSelected(isAllSelected);
        }
        adapter.notifyDataSetChanged();

    }

    @Override
    public void onCartsChange() {
        int size = ShopCartManager.getInstance().getCartsSize();
        switchshowing(size);
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }


    class CartAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return ShopCartManager.getInstance().getCartsSize();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {
            ViewHolder viewHolder = null;
            final CartInfo item = ShopCartManager.getInstance().getItemAtPostion(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_cart, parent, false);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.numberPicker.setChangerListener(new NumberPicker.OnNumberValueChangerListener() {
                @Override
                public void onChanged(int value) {
                    ShopCartManager.getInstance().changeCount(item.id, value);
                }
            });
            viewHolder.numberPicker.setOnceCount(StringUtils.nullSafeParseInt(item.yunjiage));
            int total = StringUtils.nullSafeParseInt(item.zongrenshu);
            int currt = StringUtils.nullSafeParseInt(item.canyurenshu);
            viewHolder.numberPicker.setMaxCount(total - currt);
            viewHolder.numberPicker.setCurrtCount(item.count);
            viewHolder.name.setText(item.title);
            String numbertext = parent.getContext().getString(R.string.cart_progress_desc);
            String formattext = String.format(numbertext, item.zongrenshu, total - currt);
            viewHolder.progress.setText(formattext);
            viewHolder.oneCheckbox.setVisibility(isEditing ? View.VISIBLE : View.GONE);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isEditing) {
                        ShopCartManager.getInstance().selectedCart(position);
                    } else {
                        Intent intent = new Intent(parent.getContext(), GoodsDetailAcitvity.class);
                        intent.putExtra("id", item.id);
                        intent.putExtra("qishu", item.qishu);
                        parent.getContext().startActivity(intent);
                    }
                }
            });
            Glide.with(context).load(item.thumb).placeholder(R.drawable.img_blank).into(viewHolder.oneImage);
            viewHolder.oneCheckbox.setSelected(ShopCartManager.getInstance().checkSelected(item.id));
            viewHolder.goodTenLabel.setVisibility(item.yunjiage.equals("10") ? View.VISIBLE : View.GONE);
            return convertView;
        }

        /**
         * This class contains all butterknife-injected Views & Layouts from layout file 'layout_cart.xml'
         * for easy to all layout elements.
         *
         * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
         */
        class ViewHolder {
            @Bind(R.id.one_checkbox)
            ImageButton oneCheckbox;
            @Bind(R.id.one_image)
            ImageView oneImage;
            @Bind(R.id.name)
            TextView name;
            @Bind(R.id.progress)
            TextView progress;
            @Bind(R.id.numberLabel)
            TextView numberLabel;
            @Bind(R.id.numberPicker)
            NumberPicker numberPicker;
            @Bind(R.id.regularBuyLabel)
            TextView regularBuyLabel;
            @Bind(R.id.regularBuyInput)
            TextView regularBuyInput;
            @Bind(R.id.hint)
            TextView hint;
            @Bind(R.id.goods_free_label)
            ImageView goodsFreeLabel;
            @Bind(R.id.good_ten_label)
            ImageView goodTenLabel;
            @Bind(R.id.limit_duobao_id)
            ImageView limitDuobaoId;
            @Bind(R.id.custom_top_left_icon)
            ImageView customTopLeftIcon;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == actionEdit) {
            isEditing = !isEditing;
            changeEditing();
            adapter.notifyDataSetChanged();
        }
        if (v == cartMultiCheckbox) {
            isAllSelected = !isAllSelected;
            ShopCartManager.getInstance().selectedAllCarts(isAllSelected);
        }
        if (v == cartMultiDelBtn) {
            if (ShopCartManager.getInstance().getSelectCounts() == 0) {
                showToastMessage(getString(R.string.cart_multi_del_empty));
            } else {
                createHintDialog(null, "确定删除么");
                dialog.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ShopCartManager.getInstance().removeSelectedCarts();
                    }
                }).setCancelable(false).setPositiveButton("取消", null).show();

            }
        }
        if (v == go) {
            ChangePageEvent pageEvent = new ChangePageEvent();
            pageEvent.animation = true;
            EventBus.getDefault().post(pageEvent);
        }
        if (v == submit) {
            boolean isLogin = SharePreferencesUtils.getBoolean(context, SharePreferencesUtils.ISLOGIN);
            if (isLogin) {
                if (PhoneCheckUtils.checkphone(context)) {
                    intent(OrderAcitvity.class);
                } else {
                    intent(BindActivity.class);
                }
            } else {
                intent(LoginActivity.class);
            }
        }
    }

    private void changeEditing() {
        actionEdit.setText(!isEditing ? R.string.action_edit : R.string.action_done);

        if (isEditing) {
            if (checkedFooter == null) {
                checkedFooter = cartMultiViewStub.inflate();
                cartMultiCheckbox = (ImageButton) checkedFooter.findViewById(R.id.cart_multi_checkbox);
                cartMultiSummary = (TextView) checkedFooter.findViewById(R.id.cart_multi_summary);
                cartMultiDelBtn = (Button) checkedFooter.findViewById(R.id.cart_multi_del_btn);
                cartMultiCheckbox.setOnClickListener(this);
                cartMultiDelBtn.setOnClickListener(this);
            }
            footer.setVisibility(View.GONE);
            checkedFooter.setVisibility(View.VISIBLE);

        } else {
            isAllSelected = false;

            if (ShopCartManager.getInstance().getCartsSize() == 0) {
                if (checkedFooter != null) {
                    checkedFooter.setVisibility(View.GONE);
                }
                footer.setVisibility(View.GONE);
            } else {
                if (checkedFooter != null) {
                    checkedFooter.setVisibility(View.GONE);
                }
                footer.setVisibility(View.VISIBLE);
            }
            checkShowing();
        }

    }


}
